class $httpFetch{
	constructor(requestUrl){
        this.requestUrl=requestUrl
        this.requestConfig={
            headers:{
              'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            mode: "cors",//跨域
          };
    }
    get(url,data){
        let dataStr = '';
        Object.keys(data).forEach(key => {
         dataStr = dataStr + key + '=' + data[key] + '&';
        })
        if(dataStr){
            url=url+'?'+dataStr.substring(0,dataStr.length-1)
        }
        Object.defineProperties(this.requestConfig, {
            'method:':{
                value:'GET'
            }
        })
        this.httpFetch(url,data)
    }
    post(url,data){
        let formBody = new URLSearchParams();
        for(let k in data){
            if(typeof data[k] =='object'){
                formBody.append(k,JSON.stringify(data[k]))
            }else{
                formBody.append(k,data[k])
            }
        }
        this.requestConfig['body']=formBody
        this.requestConfig['method']='POST'
        this.httpFetch(url,data)
    }
    async httpFetch(url,data){
        if(!window.fetch){
            throw new Error('浏览器不支持fetch')
            return false
        }
        try {
            let response = fetch(this.requestUrl.trim()+url,this.requestConfig)
            response=await this.processResult(response)
            return response
        } catch (error) {
            return Promise.reject(error);
        }
        
    }
    async processResult(response){
        let _response=await this.checkStatus(response)
        _response = await this.parseResult(_response);
        return _response;
    }
    checkStatus(response) {//检查响应状态
        if(response.status >= 200 && response.status < 300) {//响应成功
            return response;
        }
        if(response.status === 301 || response.status === 302) {//重定向
            window.location = response.headers.get('Location');
        }
        const error = new Error(response.statusText);
        error.data = response;
        throw error;
    }
    async parseResult(){//处理不同类型的结果
        const contentType = response.headers.get('Content-Type');
        if(contentType != null) {
            if(contentType.indexOf('text') > -1) {
                return await response.text()
            }
            if(contentType.indexOf('form') > -1) {
                return await response.formData();
            }
            if(contentType.indexOf('video') > -1) {
                return await response.blob();
            }
            if(contentType.indexOf('json') > -1) {
                return await response.json();
            }
        }
        return await response.text();
    }
}
export default $httpFetch